package com.ken.common.core.exception;

import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.ken.common.core.utils.JsonUtils;
import com.ken.entity.base.protocol.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@ConditionalOnClass(WebExceptionHandler.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class SentinelFluxException implements WebExceptionHandler {

    @Override
    public Mono handle(ServerWebExchange exchange, Throwable e) {
        log.error("[Sentinel-WebFlux-Exception] - 触发sentinel异常！", e);

        R result = new R();
        //服务器异常码
        result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());

        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            result.setMessage("服务器被限流！");
        } else if (e instanceof DegradeException) {
            result.setMessage("服务器被降级！");
        }

        //输出结果！
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8;");

        //封装返回结果
        DataBuffer dataBuffer = response.bufferFactory().wrap(JsonUtils.obj2Json(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
